import {ElMessage} from "element-plus";

export const isLoggedIn = () =>{
    return !!localStorage.getItem('token')
}

export const getToken = () => {
    return localStorage.getItem('token')
}

//返回一个带有Brear的token
export const getBearerToken = () => {
    const token = getToken()
    return token ? `Bearer${token}` : null;
}

export const logout = () =>{
    const userRole = localStorage.getItem('userRole')
    localStorage.removeItem('token')
    localStorage.removeItem('userRole') // Clear the user role
    ElMessage.success('退出成功')
    if(userRole === 'admin'){
        window.location.href = '/login'
    }else{
        window.location.href = '/user/login'
    }
}

//token有效验证
export const checkToken = async () => {
    const token = getToken()
    //格式验证
    if(!token || token.split('.').length!==3){
        console.log("token格式不正确");
        return false
    }

    //过期时间检测
    try{
        const payload = JSON.parse(atob(token.split('.')[1]))
        if(payload.exp && payload.exp*1000<Date.now()){
            ElMessage.error('登录已过期，请重新登录')
            return false
        }
    }catch {
        return false
    }
    return true
}
//获取用户角色
export const getUserRole = () => {
    return localStorage.getItem('userRole') || 'user'
}

//设置用户角色
export const setUserRole = (role) => {
    localStorage.setItem('userRole', role)
}